'use client';

import React, { createContext, useState, useCallback, ReactNode } from 'react';

interface PortalContextType {
  addToPortal: (key: string, element: ReactNode) => void;
  removeFromPortal: (key: string) => void;
}

export const PortalContext = createContext<PortalContextType>({
  addToPortal: () => {},
  removeFromPortal: () => {},
});

interface PortalProviderProps {
  children: ReactNode;
}

export const PortalProvider: React.FC<PortalProviderProps> = ({ children }) => {
  const [portals, setPortals] = useState<{ [key: string]: ReactNode }>({});

  const addToPortal = useCallback((key: string, element: ReactNode) => {
    setPortals((prev) => ({ ...prev, [key]: element }));
  }, []);

  const removeFromPortal = useCallback((key: string) => {
    setPortals((prev) => {
      const newPortals = { ...prev };
      delete newPortals[key];
      return newPortals;
    });
  }, []);

  return (
    <PortalContext.Provider value={{ addToPortal, removeFromPortal }}>
      {children}
      {Object.entries(portals).map(([key, element]) => (
        <React.Fragment key={key}>{element}</React.Fragment>
      ))}
    </PortalContext.Provider>
  );
};